package com.anstudio.app.lhasa.core.daos;

import com.anstudio.app.lhasa.core.mappers.SightMapper;
import com.anstudio.app.lhasa.core.modules.Sight;
import com.anstudio.app.lhasa.core.modules.SightExample;

import java.util.List;
import java.util.Optional;

import static com.anstudio.app.lhasa.common.consts.Constants.REFERENCE_LATITUDE_DELTA;
import static com.anstudio.app.lhasa.common.consts.Constants.REFERENCE_LONGITUDE_DELTA;

public class SightDao extends BaseDao {

    public List<Sight> queryAllSights() {
        List<Sight> ret = null;

        startSession();
        SightMapper mapper = session.getMapper(SightMapper.class);
        SightExample example = new SightExample();
        example.createCriteria().andIdIsNotNull();
        ret = mapper.selectByExampleWithBLOBs(example);
        endSession();

        return ret;
    }

    public Optional<Sight> querySightById(int id) {
        startSession();
        SightMapper mapper = session.getMapper(SightMapper.class);
        SightExample example = new SightExample();
        example.createCriteria().andIdEqualTo(id);
        List<Sight> sights = mapper.selectByExampleWithBLOBs(example);
        Optional ret = sights.isEmpty() ? Optional.empty() : Optional.of(sights.get(0));
        endSession();
        return ret;
    }

    public Optional<Sight> querySightByGPS(float latitude, float langitude) {
        startSession();
        SightMapper mapper = session.getMapper(SightMapper.class);
        SightExample example = new SightExample();
        example.createCriteria()
                .andLatiBetween(latitude - REFERENCE_LATITUDE_DELTA, latitude + REFERENCE_LATITUDE_DELTA)
                .andLongiBetween(langitude - REFERENCE_LONGITUDE_DELTA, langitude + REFERENCE_LONGITUDE_DELTA);
        List<Sight> sights = mapper.selectByExampleWithBLOBs(example);
        Optional ret = sights.isEmpty() ? Optional.empty() : Optional.of(sights.get(0));
        endSession();

        return ret;
    }

    public Optional<Sight> querySightByName(String name) {
        startSession();
        SightMapper mapper = session.getMapper(SightMapper.class);
        SightExample example = new SightExample();
        example.createCriteria().andNameEqualTo(name);
        List<Sight> sights = mapper.selectByExampleWithBLOBs(example);
        Optional ret = sights.isEmpty() ? Optional.empty() : Optional.of(sights.get(0));
        endSession();

        return ret;
    }

    public Object getObjectById(int id) {
        return getDao(SightDao.class, DEFAULT_KEY);
    }

    public static SightDao getDao() {
        return getDao(SightDao.class, DEFAULT_KEY);
    }
}
